import React, { useEffect, useRef } from "react";
import pointIcon from '@/assets/point2.png';
import pointIcon2 from '@/assets/point3.png';


interface ChildProps {
    data: { type: string; value: [] };
}
const BMapComponent2: React.FC<ChildProps> = ({ data }) => {
    const mapRef = useRef<HTMLDivElement>(null);
    const map = useRef<any>(null); // 地图实例
    const polylines = useRef<any>(null); // 当前绘制路线
    const allpoints = useRef<any>([]); // 所有点位
    const labels = useRef<any>([])   //所有标注
    // const drivingService = useRef<any>(null)
    useEffect(() => {
        // 确保地图加载完成后再初始化oint
        const initMap = () => {
            if (!mapRef.current) return;
            map.current = new window.BMapGL.Map(mapRef.current);
            // 设置中心点
            const point = new window.BMapGL.Point(116.405, 39.920);
            map.current.centerAndZoom(point, 11);
            // 启用滚轮缩放
            map.current.enableScrollWheelZoom(true);
            // 添加控件
            map.current.addControl(new window.BMapGL.ZoomControl());
            map.current.addControl(new window.BMapGL.ScaleControl())
        };
        // 判断是否已经加载了 BMapGL
        if (window.BMapGL && window.BMapGL.Map) {
            initMap();
        } else {
            // 如果未加载，定义全局回调
            window.BMapGL.onBMapLoad = () => {
                initMap();
            };
        }
    }, []);
    useEffect(() => {
        if (data.type == 'polyline') {
            createPolyline(data.value)
        }
        if (data.type == 'point') {
            // createPoints(data.value)
        }
    }, [data]);


    //绘制地图中心点
    const setCenter = (obj: any) => {
        const point = new window.BMapGL.Point(obj.lng, obj.lat);
        map.current.centerAndZoom(point, 11);
    }

    //绘制点位
    const createPoints = (arr: any) => {
        arr.forEach((i: any, index: any) => {
            const iconToUse = index === 0 ? pointIcon : pointIcon2;

            const myIcon = new window.BMapGL.Icon(
                iconToUse,
                new window.BMapGL.Size(20, 30),
                {
                    anchor: new window.BMapGL.Size(10, 20)
                }
            );
            let point = new window.BMapGL.Point(i.lng, i.lat)
            let marker = new window.BMapGL.Marker(point, { icon: myIcon });

            // 创建自定义 Label（HTML 内容）
            const labelContent = `
            <div style="
            background: ${index === 0
                    ? 'linear-gradient(135deg, #2563EB 0%, #2563EB 100%)'
                    : 'linear-gradient(135deg, #FF6B6B 0%, #FF4141 100%)'
                };
             color: white;
             padding: 4px 8px;
             border-radius: 6px;
             font-size: 14px;
             font-weight: bold;
             white-space: nowrap;
             box-shadow: 0 2px 4px rgba(0,0,0,0.3);
             transform: translateX(8px);
           ">
             ${index == 0 ? '始' : '收'}
            <span style="
            background: rgba(255,255,255,0.2);
            padding: 0 4px;
            border-radius: 4px;
            font-size: 14px;
            margin-left: 4px;
           ">${i.place}</span>
           </div>
           `;
            const label = new window.BMapGL.Label(labelContent, {
                position: point,
                offset: new window.BMapGL.Size(15, 0) // 向右偏移，避免遮挡图标
            });
            // 必须设置此属性，否则 HTML 不会渲染
            label.setStyle({
                border: 'none',
                background: 'none',
                boxShadow: 'none',
                padding: 0,
                margin: 0
            });
            // 允许 Label 显示 HTML
            label.enableMassClear = false;
            map.current.addOverlay(label);
            labels.current.push(label);
            // const content = `
            //        <div style="padding: 10px; margin-top: -16px">
            //        <h4 style="margin: 0 0 5px 0;">${i.place}</h4>
            //        <p style="margin: 0; font-size: 12px;">经纬度：${i.lng}, ${i.lat}</p>
            //       </div>
            //       `
            // 创建信息窗口
            // const infoWindow = new window.BMapGL.InfoWindow(content, {
            //     width: 50,
            //     height: 70,
            //     title: "",
            //     offset: new window.BMapGL.Size(0, -10), // 向上偏移 10 像素
            // });
            // marker.addEventListener("click", () => {
            //     map.current.openInfoWindow(infoWindow, point);
            // });
            map.current.addOverlay(marker);
            allpoints.current.push(marker)
        })
    }
    //规划行车路线，待用
    // const createPolyline = (arr: any) => {

    //     // 1. 清理之前的路线和标记
    //     if (drivingService.current) {
    //         drivingService.current.clearResults(); //清除所有自动绘制的 Overlay
    //         drivingService.current = null
    //     }
    //     clearAllMarkers(); // 清除所有标记点
    //     // createPoints(arr)
    //     if (arr.length < 2) {
    //         console.warn("至少需要两个点才能规划路线");
    //         return;
    //     }

    //     // 3. 创建驾车路线服务实例
    //     drivingService.current = new window.BMapGL.DrivingRouteLine(map.current, {
    //         renderOptions: {
    //             map: map.current,
    //             autoViewport: true,// 是否自动调整地图视野
    //             // enableDragging: true,
    //         },
    //         policy: 0,
    //         onSearchComplete: function (results: any) {
    //             // 路线规划完成后的回调函数
    //             if (drivingService.current.getStatus() === window.BMAP_STATUS_SUCCESS) {
    //                 // 获取第一条路线（通常是最优路线）
    //                 console.log(results, '结果')
    //                 console.log("路线总数：" + results.getNumPlans());
    //                 console.log(results.getPlan(0).getDuration(true), '驾驶时间')
    //                 console.log(results.getPlan(0).getDistance(true), '驾驶距离')

    //                 // 创建 Polyline，DrivingRouteLine会自动添加线路，也可手动添加
    //                 //const firstRoute = results.getPlan(0).getRoute(0);
    //                 // const pathPoints = firstRoute.getPath();
    //                 // const realPolyline = new window.BMapGL.Polyline(pathPoints, {
    //                 //     strokeStyle: 'solid',
    //                 //     strokeColor: '#758DD1', // 初始颜色
    //                 //     strokeWeight: 8,
    //                 //     strokeOpacity: 0.8,
    //                 // });
    //                 // 5. 将路线添加到地图
    //                 // map.current.addOverlay(realPolyline);
    //                 // polylines.current = realPolyline;

    //                 // 6. 设置地图中心到第一个点 (可选，也可以让路线服务自动调整视野)
    //                 // setCenter(arr[0]);

    //                 // let currentColor = '#758DD1';
    //                 // const intervalId = setInterval(() => {
    //                 //     currentColor = currentColor === '#758DD1' ? '#7BAD8D' : '#758DD1';
    //                 //     if (polylines.current) {
    //                 //         polylines.current.setStrokeColor(currentColor);
    //                 //     } else {
    //                 //         clearInterval(intervalId); // 如果 polyline 被清除，停止定时器
    //                 //     }
    //                 // }, 400);
    //             } else {
    //                 console.error("路线规划失败:", drivingService.current.getStatus());
    //             }
    //         }
    //     });
    //     const start = new window.BMapGL.Point(arr[0].lng, arr[0].lat);
    //     const end = new window.BMapGL.Point(arr[arr.length - 1].lng, arr[arr.length - 1].lat);
    //     const waypoints = arr.slice(1, arr.length - 1).map((point: any) =>
    //         new window.BMapGL.Point(point.lng, point.lat)
    //     );
    //     // 发起路线规划请求

    //     drivingService.current.search(start, end, { waypoints: waypoints, tactics: 2 });
    // };


    //绘制当前线路 
    const createPolyline = (arr: any) => {
        if (polylines.current) {
            map.current.removeOverlay(polylines.current);
            polylines.current = null
        }
        clearAllMarkers()
        clearAllLabels()
        createPoints(arr)
        setCenter(arr[0])
        let data = arr.map((i: any) => {
            return new window.BMapGL.Point(i.lng, i.lat)
        })

        //每段折线中点添加距离
        for (let i = 0; i < arr.length - 1; i++) {
            const pointA = data[i];
            const pointB = data[i + 1];
            const distancet = arr[i].distancet;
            const midLng = (pointA.lng + pointB.lng) / 2;
            const midLat = (pointA.lat + pointB.lat) / 2;
            const midPoint = new window.BMapGL.Point(midLng, midLat);
            const label = new window.BMapGL.Label(`${distancet}km`, {
                position: midPoint,
                offset: new window.BMapGL.Size(0, -10), // 微调位置，避免遮挡线路
            });
            label.setStyle({
                backgroundColor: 'rgba(0, 0, 0, 0.6)',
                color: '#fff',
                padding: '4px 8px',
                borderRadius: '4px',
                fontSize: '12px',
                border: 'none',
                whiteSpace: 'nowrap',
            });

            map.current.addOverlay(label);
            labels.current.push(label);
        }

        //设置折线颜色
        let currentColor = 'red'
        let polyline = new window.BMapGL.Polyline(data, {
            strokeStyle: 'solid',
            strokeColor: currentColor,
            strokeWeight: 4,
            strokeOpacity: 0.8,
        });
        map.current.addOverlay(polyline);
        polylines.current = polyline
        // map.current.setViewport(data, {
        //     animate: true       //自动调整地图层级，确保所有点位在视野内
        // });
        // setInterval(() => {
        //     currentColor = currentColor === 'red' ? 'blue' : 'red';
        //     polyline.setStrokeColor(currentColor);
        // }, 400);
    }




    //清除所有点位
    const clearAllMarkers = () => {
        const overlays = map.current.getOverlays();
        overlays.forEach((i: any) => {
            if (i instanceof window.BMapGL.Marker) {
                map.current.removeOverlay(i);
            }
        });
        allpoints.current = []
    };
    //清除所有label
    const clearAllLabels = () => {
        labels.current.forEach((i: any) => {
            map.current.removeOverlay(i);
        });
        labels.current = [];
    }

    return <div ref={mapRef}
        style={{ width: '100%', height: '100%', border: '1px solid #ccc' }}></div>


}

export default BMapComponent2






